//
// Created by sunyl on 25-5-10.
//

#include "key.h"
#include "gpio.h"
#include "stm32f1xx.h"
#define NUM_KEYS 4

Key_t keys[NUM_KEYS] = {
        {KEY_UP_GPIO_Port, KEY_UP_Pin,GPIO_PIN_SET,KEY_IDLE, 0, 0},
        {KEY0_GPIO_Port, KEY0_Pin, GPIO_PIN_RESET,KEY_IDLE, 0, 0},
        {KEY1_GPIO_Port, KEY1_Pin, GPIO_PIN_RESET,KEY_IDLE, 0, 0},
        {KEY2_GPIO_Port, KEY2_Pin, GPIO_PIN_RESET,KEY_IDLE, 0, 0}
};

void KeyScan(void)
{
    for (int i = 0; i < NUM_KEYS; i++)
    {
        GPIO_PinState pin = HAL_GPIO_ReadPin(keys[i].port, keys[i].pin);
        switch (keys[i].state)
        {
            case KEY_IDLE:
                if (pin == keys[i].activeLevel)
                {
                    keys[i].state    = KEY_DEBOUNCE;
                    keys[i].lastTick = HAL_GetTick();
                }
                break;

            case KEY_DEBOUNCE:
                if (HAL_GetTick() - keys[i].lastTick >= 20)
                {
                    // 再次确认
                    if (HAL_GPIO_ReadPin(keys[i].port, keys[i].pin) == keys[i].activeLevel)
                    {
                        keys[i].state = KEY_PRESSED;
                        keys[i].flag  = 1;
                    }
                    else
                    {
                        keys[i].state = KEY_IDLE;
                    }
                }
                break;

            case KEY_PRESSED:
                // 松开时，电平 != activeLevel
                if (pin != keys[i].activeLevel)
                {
                    keys[i].state = KEY_IDLE;
                }
                break;
        }
    }
}
